#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
实例信息查询脚本
提供详细的实例信息查询功能
"""

import requests
import json
import time
import sys
from typing import Dict, List, Any, Optional
from datetime import datetime
import argparse

class InstanceInfoQuery:
    """实例信息查询器"""
    
    def __init__(self, base_url: str = "http://localhost:8080"):
        self.base_url = base_url
    
    def get_system_status(self) -> Dict[str, Any]:
        """获取系统状态"""
        try:
            response = requests.get(f"{self.base_url}/api/v1/system/status", timeout=10)
            if response.status_code == 200:
                return response.json()
            else:
                print(f"❌ 获取系统状态失败: {response.status_code}")
                return {}
        except Exception as e:
            print(f"❌ 连接失败: {e}")
            return {}
    
    def get_servers(self) -> List[Dict[str, Any]]:
        """获取所有服务器列表"""
        try:
            response = requests.get(f"{self.base_url}/api/v1/servers", timeout=10)
            if response.status_code == 200:
                data = response.json()
                if data.get('success'):
                    return data.get('data', [])
            else:
                print(f"❌ 获取服务器列表失败: {response.status_code}")
                return []
        except Exception as e:
            print(f"❌ 连接失败: {e}")
            return []
    
    def get_server_detail(self, instance_id: str) -> Optional[Dict[str, Any]]:
        """获取单个服务器的详细信息"""
        try:
            response = requests.get(f"{self.base_url}/api/v1/servers/{instance_id}", timeout=10)
            if response.status_code == 200:
                data = response.json()
                if data.get('success'):
                    return data.get('data')
            else:
                print(f"❌ 获取服务器详情失败: {response.status_code}")
                return None
        except Exception as e:
            print(f"❌ 连接失败: {e}")
            return None
    
    def format_status(self, status: str) -> str:
        """格式化状态显示"""
        status_map = {
            'PENDING': '⏳ 启动中',
            'RUNNING': '✅ 运行中',
            'STOPPING': '🛑 停止中',
            'STOPPED': '⏸️ 已停止',
            'TERMINATED': '❌ 已终止',
            'UNKNOWN': '❓ 未知'
        }
        return status_map.get(status, f'❓ {status}')
    
    def format_region(self, region: str) -> str:
        """格式化地域显示"""
        region_map = {
            'ap-beijing': '🏛️ 北京',
            'ap-nanjing': '🏛️ 南京',
            'ap-guangzhou': '🏛️ 广州',
            'ap-shanghai': '🏛️ 上海',
            'ap-chongqing': '🏛️ 重庆'
        }
        return region_map.get(region, f'🌍 {region}')
    
    def format_gpu_type(self, gpu_type: str) -> str:
        """格式化GPU类型显示"""
        gpu_map = {
            'basic': '🎮 基础型 (3.6元/h)',
            'standard': '🎮 标准型 (7.2元/h)',
            'performance': '🎮 性能型 (1.2元/h)',
            'advanced': '🎮 高级型 (2.4元/h)',
            'premium': '🎮 高端型 (3.3元/h)'
        }
        return gpu_map.get(gpu_type, f'🎮 {gpu_type}')
    
    def calculate_uptime(self, created_time: str) -> str:
        """计算运行时间"""
        try:
            if not created_time:
                return "未知"
            
            # 解析创建时间
            if isinstance(created_time, (int, float)):
                created_timestamp = created_time
            else:
                # 假设是ISO格式字符串
                created_timestamp = datetime.fromisoformat(created_time.replace('Z', '+00:00')).timestamp()
            
            uptime_seconds = time.time() - created_timestamp
            
            if uptime_seconds < 60:
                return f"{int(uptime_seconds)}秒"
            elif uptime_seconds < 3600:
                return f"{int(uptime_seconds/60)}分钟"
            elif uptime_seconds < 86400:
                return f"{int(uptime_seconds/3600)}小时{int((uptime_seconds%3600)/60)}分钟"
            else:
                days = int(uptime_seconds/86400)
                hours = int((uptime_seconds%86400)/3600)
                return f"{days}天{hours}小时"
        except:
            return "未知"
    
    def show_system_overview(self):
        """显示系统概览"""
        print("📊 HAI优化系统概览")
        print("=" * 60)
        
        status = self.get_system_status()
        if not status or not status.get('success'):
            print("❌ 无法获取系统状态")
            return
        
        data = status['data']
        
        # 系统基本信息
        print(f"🖥️  系统状态: {'✅ 运行中' if data['system']['running'] else '❌ 已停止'}")
        print(f"🔄 扩缩容状态: {'✅ 运行中' if data['scaling']['running'] else '❌ 已停止'}")
        print(f"⏰ 系统运行时间: {self.calculate_uptime(data['system']['start_time'])}")
        print()
        
        # 服务器统计
        servers_info = data['servers']['servers']
        print("🖥️  服务器统计:")
        print(f"  总服务器数: {servers_info['total']}")
        print(f"  可用服务器: {servers_info['available']}")
        print(f"  健康服务器: {servers_info['healthy']}")
        print(f"  总容量: {servers_info['total_capacity']}")
        print(f"  已用容量: {servers_info['used_capacity']}")
        print(f"  利用率: {servers_info['utilization_rate']:.1%}")
        print()
        
        # 任务统计
        tasks_info = data['servers']['tasks']
        print("📋 任务统计:")
        print(f"  总任务数: {tasks_info['total']}")
        print(f"  已完成: {tasks_info['completed']}")
        print(f"  处理中: {tasks_info['processing']}")
        print(f"  队列中: {tasks_info['queued']}")
        print(f"  失败数: {tasks_info['failed']}")
        print()
        
        # 队列信息
        queue_info = data['queue']
        print("📊 队列信息:")
        print(f"  全局队列长度: {queue_info['global_queue_length']}")
        print(f"  活跃用户数: {queue_info['active_users']}")
        print(f"  总任务数: {queue_info['total_tasks_in_queue']}")
        print()
        
        # 扩缩容统计
        scaling_info = data['statistics']
        print("🔄 扩缩容统计:")
        print(f"  总扩缩容次数: {scaling_info['total_scaling_actions']}")
        print(f"  总创建服务器: {scaling_info['total_servers_created']}")
        print(f"  总销毁服务器: {scaling_info['total_servers_destroyed']}")
        print(f"  总处理任务: {scaling_info['total_tasks_processed']}")
        print(f"  总成功任务: {scaling_info['total_tasks_successful']}")
        print(f"  总失败任务: {scaling_info['total_tasks_failed']}")
        print()
    
    def show_servers_list(self, detailed: bool = False):
        """显示服务器列表"""
        print("📋 服务器实例列表")
        print("=" * 60)
        
        servers = self.get_servers()
        if not servers:
            print("❌ 无法获取服务器列表")
            return
        
        print(f"共找到 {len(servers)} 个服务器实例:")
        print()
        
        for i, server in enumerate(servers, 1):
            instance_id = server.get('instance_id', 'Unknown')
            status = server.get('status', 'Unknown')
            region = server.get('region', 'Unknown')
            gpu_type = server.get('gpu_type', 'Unknown')
            
            print(f"🖥️  实例 {i}: {instance_id}")
            print(f"   状态: {self.format_status(status)}")
            print(f"   地域: {self.format_region(region)}")
            print(f"   GPU类型: {self.format_gpu_type(gpu_type)}")
            
            if detailed:
                # 显示详细信息
                detail = self.get_server_detail(instance_id)
                if detail:
                    print(f"   CPU使用率: {detail.get('cpu_usage', 0):.1f}%")
                    print(f"   GPU使用率: {detail.get('gpu_usage', 0):.1f}%")
                    print(f"   内存使用率: {detail.get('memory_usage', 0):.1f}%")
                    print(f"   当前任务数: {detail.get('current_tasks', 0)}")
                    print(f"   最大并发数: {detail.get('max_concurrent_tasks', 0)}")
                    print(f"   创建时间: {detail.get('created_time', '未知')}")
                    print(f"   运行时间: {self.calculate_uptime(detail.get('created_time'))}")
            
            print()
    
    def show_server_detail(self, instance_id: str):
        """显示单个服务器的详细信息"""
        print(f"🔍 服务器详细信息: {instance_id}")
        print("=" * 60)
        
        detail = self.get_server_detail(instance_id)
        if not detail:
            print("❌ 无法获取服务器详细信息")
            return
        
        print(f"🆔 实例ID: {detail.get('instance_id', 'Unknown')}")
        print(f"📊 状态: {self.format_status(detail.get('status', 'Unknown'))}")
        print(f"🌍 地域: {self.format_region(detail.get('region', 'Unknown'))}")
        print(f"🎮 GPU类型: {self.format_gpu_type(detail.get('gpu_type', 'Unknown'))}")
        print()
        
        print("📈 性能指标:")
        print(f"   CPU使用率: {detail.get('cpu_usage', 0):.1f}%")
        print(f"   GPU使用率: {detail.get('gpu_usage', 0):.1f}%")
        print(f"   内存使用率: {detail.get('memory_usage', 0):.1f}%")
        print()
        
        print("📋 任务信息:")
        print(f"   当前任务数: {detail.get('current_tasks', 0)}")
        print(f"   最大并发数: {detail.get('max_concurrent_tasks', 0)}")
        print(f"   任务完成数: {detail.get('completed_tasks', 0)}")
        print(f"   任务失败数: {detail.get('failed_tasks', 0)}")
        print()
        
        print("⏰ 时间信息:")
        print(f"   创建时间: {detail.get('created_time', '未知')}")
        print(f"   运行时间: {self.calculate_uptime(detail.get('created_time'))}")
        print(f"   最后更新: {detail.get('last_updated', '未知')}")
        print()
        
        print("🌐 网络信息:")
        print(f"   端点: {detail.get('endpoint', '未知')}")
        print(f"   健康检查: {'✅ 正常' if detail.get('health_check', False) else '❌ 异常'}")
        print()
    
    def show_statistics(self):
        """显示统计信息"""
        print("📊 系统统计信息")
        print("=" * 60)
        
        status = self.get_system_status()
        if not status or not status.get('success'):
            print("❌ 无法获取系统状态")
            return
        
        data = status['data']
        
        # 地域分布统计
        print("🌍 地域分布:")
        region_stats = data['hai']['real_apps']['region_statistics']
        for region, stats in region_stats.items():
            region_name = self.format_region(region)
            print(f"   {region_name}: {stats['healthy']}/{stats['total']} 健康应用")
        print()
        
        # GPU类型分布
        servers = self.get_servers()
        if servers:
            gpu_stats = {}
            for server in servers:
                gpu_type = server.get('gpu_type', 'unknown')
                gpu_stats[gpu_type] = gpu_stats.get(gpu_type, 0) + 1
            
            print("🎮 GPU类型分布:")
            for gpu_type, count in gpu_stats.items():
                gpu_name = self.format_gpu_type(gpu_type)
                print(f"   {gpu_name}: {count} 个实例")
            print()
        
        # 状态分布
        if servers:
            status_stats = {}
            for server in servers:
                status = server.get('status', 'unknown')
                status_stats[status] = status_stats.get(status, 0) + 1
            
            print("📊 状态分布:")
            for status, count in status_stats.items():
                status_name = self.format_status(status)
                print(f"   {status_name}: {count} 个实例")
            print()

def main():
    parser = argparse.ArgumentParser(description='HAI实例信息查询工具')
    parser.add_argument('action', choices=['overview', 'list', 'detail', 'stats'], 
                       help='查询类型')
    parser.add_argument('--instance-id', type=str, 
                       help='实例ID (仅用于detail操作)')
    parser.add_argument('--detailed', action='store_true',
                       help='显示详细信息 (仅用于list操作)')
    parser.add_argument('--url', default='http://localhost:8080', 
                       help='HAI优化系统URL')
    
    args = parser.parse_args()
    
    query = InstanceInfoQuery(args.url)
    
    if args.action == 'overview':
        query.show_system_overview()
    elif args.action == 'list':
        query.show_servers_list(detailed=args.detailed)
    elif args.action == 'detail':
        if not args.instance_id:
            print("❌ 请提供实例ID")
            sys.exit(1)
        query.show_server_detail(args.instance_id)
    elif args.action == 'stats':
        query.show_statistics()

if __name__ == '__main__':
    main()
